package com.ye.controller;

import com.ye.domain.R;
import com.ye.domain.User;
import com.ye.service.UserService;
import com.ye.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@RefreshScope
public class LoginController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    @PostMapping("/user/login")
    public R login(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request) {

//        1.获取前端请求携带的Token
        String token = request.getHeader("token");
        if (token != null) {
            //    从redis获取对应token的值（User）,存在对应值就返回，不存在则返回空
            Object o = redisTemplate.opsForValue().get(token);
            if (o != null) {
                System.out.println("基于redis登录");  //Test
                return R.ok(o, token);
            }
            System.out.println("redis无用户缓存");
            return R.error(400, "缓存失效，请重新登录");
        }

//        2.当token为空，调用登录API，生成token并保存至redis,设置缓存时间
        User loginUser = userService.login(username, password);
        if (loginUser == null) {
            return R.error(400, "用户名或密码错误");
        }
        String signature = Md5Util.signature(loginUser);
        System.out.println("token====>>>>>" + signature);  //Test
        redisTemplate.opsForValue().set(signature, loginUser, 1, TimeUnit.DAYS);
        System.out.println("基于MySQL登录");  //Test
        //   返回前端用户信息+token字符串
        return R.ok(loginUser).msg(signature);
    }

    @PostMapping("/user/register")

    public R register(@RequestBody User user) {
        try {
            userService.register(user);
            return R.ok("", "成功注册");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(500, "注册失败");
        }
    }

//    //    降级逻辑
//    public R FailFallbackMethod(User user) {
//
//        return R.error(500, "请检查网络！");
//    }
//    public R defaultFallback(){
//        return R.error(500, "出现故障，可能为网络原因");
//    }
}
